package com.ikonke.iot.alarm.influxdb;

import org.influxdb.InfluxDB;
import org.influxdb.InfluxDB.ResponseFormat;
import org.influxdb.InfluxDBFactory;
import org.influxdb.dto.Pong;

import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;

/**
 * @Author: liull
 * @Description:
 * @Date: Created in 16:38 2020/5/13
 * @Modified By:
 */
@Slf4j
public class InfluxDbConnector {

    public static String defaultRetentionPolicy(String version) {
        if (version.startsWith("0.")) {
            return "default";
        } else {
            return "autogen";
        }
    }

    public static InfluxDB connectToInfluxDB(String apiUrl,
            ResponseFormat responseFormat, String username, String password) {
        OkHttpClient.Builder clientToUse = new OkHttpClient.Builder();
        InfluxDB influxDB = InfluxDBFactory.connect(apiUrl, username, password, clientToUse, responseFormat);
        boolean influxDBstarted = false;
        do {
            Pong response;
            try {
                response = influxDB.ping();
                if (response.isGood()) {
                    influxDBstarted = true;
                }
            } catch (Exception e) {
                // NOOP intentional
                e.printStackTrace();
            }
            try {
                Thread.sleep(100L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } while (!influxDBstarted);
        influxDB.setLogLevel(InfluxDB.LogLevel.NONE);
        log.info("##################################################################################");
        log.info("#  Connected to InfluxDB Version: " + influxDB.version() + " #");
        log.info("##################################################################################");
        return influxDB;
    }
}